<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
import { ElMessage } from "element-plus";
import { registerMessageListener, removeMessageListener } from "../api/ws.js";
import { getAllMsg, updateMsgStatus } from "../api/usermessage.js";
import dayjs from "dayjs";

const messages = ref([]);
const userId = Number(localStorage.getItem("userId"));
const loading = ref(false);

const currentPage = ref(1);
const pageSize = 2; // ✅ 每页显示两条

const totalPages = computed(() => {
  return Math.ceil(messages.value.length / pageSize);
});

const paginatedMessages = computed(() => {
  const start = (currentPage.value - 1) * pageSize;
  return messages.value.slice(start, start + pageSize);
});

const isReadFromStatus = (status) => status === "READ";

const loadHistory = async () => {
  loading.value = true;
  try {
    const res = await getAllMsg(userId);
    if (res.data && res.data.code === 200) {
      messages.value = res.data.data.map((msg) => ({
        title: msg.title,
        content: msg.content,
        sendTime: msg.sendTime,
        msgStatus: msg.msgStatus,
        msgId: msg.msgId,
        read: isReadFromStatus(msg.msgStatus),
      }));
    }
  } catch (err) {
    console.error("获取历史消息失败", err);
  } finally {
    loading.value = false;
  }
};

const handleMessage = (msg) => {
  messages.value.unshift({
    ...msg,
    read: false,
  });
  console.log("📨 收到服务器消息:", msg);
};

const markAsRead = async (msg) => {
  try {
    const res = await updateMsgStatus(msg.msgId);
    if (res.data && res.data.code === 200) {
      msg.read = true;
      msg.msgStatus = "READ";
      ElMessage.success("已标记为已读");
    } else {
      ElMessage.error("标记失败");
    }
  } catch (err) {
    console.error("标记已读异常", err);
    ElMessage.error("标记失败");
  }
};

const formatTime = (time) => dayjs(time).format("YYYY-MM-DD HH:mm:ss");

const nextPage = () => {
  if (currentPage.value < totalPages.value) currentPage.value++;
};
const prevPage = () => {
  if (currentPage.value > 1) currentPage.value--;
};

onMounted(() => {
  loadHistory();
  registerMessageListener(handleMessage);
});

onBeforeUnmount(() => {
  removeMessageListener(handleMessage);
});
</script>

<template>
  <div class="message-container">
    <h2 class="title">我的消息</h2>

    <div v-if="loading" class="loading">加载中...</div>

    <div v-else-if="messages.length === 0" class="no-message">
      暂无消息~
    </div>

    <!-- 消息列表 -->
    <div v-else class="message-list">
      <div
        v-for="msg in paginatedMessages"
        :key="msg.msgId"
        class="message-item"
        :class="{ read: msg.read }"
      >
        <div class="message-header">
          <h3 class="message-title">{{ msg.title }}</h3>
          <button
            v-if="!msg.read"
            @click="markAsRead(msg)"
            class="mark-btn"
          >
            标记为已读
          </button>
          <span v-else class="read-tag">已读</span>
        </div>

        <div class="message-content">{{ msg.content }}</div>

        <div class="message-footer">
          <span class="time">{{ formatTime(msg.sendTime) }}</span>
        </div>
      </div>
    </div>

    <!-- ✅ 翻页按钮固定在容器底部 -->
    <div v-if="messages.length > 2" class="pagination-container">
      <button
        class="pagination-btn"
        :disabled="currentPage === 1"
        @click="prevPage"
      >
        上一页
      </button>

      <span class="page-text">
        当前第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
      </span>

      <button
        class="pagination-btn"
        :disabled="currentPage === totalPages"
        @click="nextPage"
      >
        下一页
      </button>
    </div>
  </div>
</template>

<style scoped>
.message-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: "Arial", sans-serif;
  min-height: 80vh;
  display: flex;
  flex-direction: column;
  justify-content: space-between; /* ✅ 关键：内容 + 底部分页 */
  box-sizing: border-box;
}

/* 标题样式 */
.title {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
  font-size: 24px;
  border-bottom: 2px solid #409eff;
  padding-bottom: 10px;
}

.no-message {
  text-align: center;
  color: #999;
  font-size: 18px;
  padding: 60px 0;
  background-color: #fafafa;
  border-radius: 8px;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 25px; /* ✅ 两条消息间隔更大 */
  flex: 1;
}

/* 每条消息 */
.message-item {
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.message-item:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.message-item.read {
  background-color: #f5f7fa;
}

/* 头部 */
.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 10px;
  margin-bottom: 10px;
}

.message-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

/* 按钮样式 */
.mark-btn {
  padding: 6px 12px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.mark-btn:hover {
  background-color: #66b1ff;
  transform: translateY(-1px);
}

.read-tag {
  background-color: #67c23a;
  color: white;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 13px;
}

/* 内容 */
.message-content {
  font-size: 16px;
  color: #555;
  line-height: 1.6;
  margin-bottom: 10px;
}

/* 时间 */
.message-footer {
  text-align: right;
}

.time {
  font-size: 14px;
  color: #999;
}

/* ✅ 翻页按钮固定在容器底部 */
.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 -2px 6px rgba(0, 0, 0, 0.05);
  margin-top: 30px;
}

.pagination-btn {
  padding: 10px 20px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.pagination-btn:hover {
  background-color: #66b1ff;
  transform: translateY(-1px);
}

.pagination-btn:disabled {
  background-color: #dcdfe6;
  cursor: not-allowed;
}

.page-text {
  font-size: 16px;
  color: #666;
}

.loading {
  text-align: center;
  padding: 40px;
  color: #666;
}

.title-with-icon {
  display: flex;
  align-items: center;
  gap: 10px;
}

.msg-icon {
  width: 24px;
  height: 24px;
}
</style>
